{% extends 'base.html' %}
{% load static %}

{% block title %}高级分析仪表板 - 固定资产管理系统{% endblock %}

{% block extra_css %}
<link href="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.css" rel="stylesheet">
<style>
    .kpi-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 15px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        transition: transform 0.3s ease;
    }
    
    .kpi-card:hover {
        transform: translateY(-5px);
    }
    
    .kpi-value {
        font-size: 2.5rem;
        font-weight: bold;
        margin-bottom: 5px;
    }
    
    .kpi-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }
    
    .kpi-change {
        font-size: 0.8rem;
        margin-top: 10px;
    }
    
    .chart-container {
        background: white;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }
    
    .chart-title {
        font-size: 1.2rem;
        font-weight: bold;
        margin-bottom: 15px;
        color: #333;
    }
    
    .anomaly-item {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 10px;
    }
    
    .anomaly-item.high {
        background: #f8d7da;
        border-color: #f5c6cb;
    }
    
    .anomaly-item.medium {
        background: #fff3cd;
        border-color: #ffeaa7;
    }
    
    .date-range-selector {
        background: white;
        border-radius: 10px;
        padding: 15px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    
    .forecast-chart {
        position: relative;
        height: 300px;
    }
    
    .comparison-table {
        background: white;
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    
    .comparison-table th {
        background: #f8f9fa;
        font-weight: 600;
    }
    
    .metric-trend {
        display: inline-flex;
        align-items: center;
        margin-left: 10px;
    }
    
    .trend-up {
        color: #28a745;
    }
    
    .trend-down {
        color: #dc3545;
    }
    
    .loading-spinner {
        display: none;
        text-align: center;
        padding: 20px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-chart-line"></i> 高级分析仪表板</h2>
        <div class="btn-group">
            <button class="btn btn-outline-primary" onclick="refreshDashboard()">
                <i class="fas fa-sync-alt"></i> 刷新数据
            </button>
            <button class="btn btn-outline-success" onclick="exportReport()">
                <i class="fas fa-download"></i> 导出报告
            </button>
        </div>
    </div>
    
    <!-- 时间范围选择器 -->
    <div class="date-range-selector">
        <div class="row align-items-center">
            <div class="col-md-6">
                <h5 class="mb-0">数据时间范围</h5>
                <small class="text-muted">选择要分析的时间范围</small>
            </div>
            <div class="col-md-6">
                <div class="row">
                    <div class="col-md-4">
                        <select class="form-select" id="dateRangeSelect" onchange="updateDateRange()">
                            <option value="7" {% if selected_range == '7' %}selected{% endif %}>最近7天</option>
                            <option value="30" {% if selected_range == '30' %}selected{% endif %}>最近30天</option>
                            <option value="90" {% if selected_range == '90' %}selected{% endif %}>最近90天</option>
                            <option value="365" {% if selected_range == '365' %}selected{% endif %}>最近一年</option>
                            <option value="custom">自定义</option>
                        </select>
                    </div>
                    <div class="col-md-4" id="customStartDate" style="display: none;">
                        <input type="date" class="form-control" id="startDate" value="{{ date_range.start }}">
                    </div>
                    <div class="col-md-4" id="customEndDate" style="display: none;">
                        <input type="date" class="form-control" id="endDate" value="{{ date_range.end }}">
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- KPI指标卡片 -->
    <div class="row">
        <div class="col-md-2">
            <div class="kpi-card">
                <div class="kpi-value">{{ kpi_data.total_assets }}</div>
                <div class="kpi-label">总资产数量</div>
                <div class="kpi-change">
                    <i class="fas fa-arrow-up trend-up"></i> +5.2%
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="kpi-card">
                <div class="kpi-value">{{ kpi_data.asset_utilization }}%</div>
                <div class="kpi-label">资产利用率</div>
                <div class="kpi-change">
                    <i class="fas fa-arrow-up trend-up"></i> +2.1%
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="kpi-card">
                <div class="kpi-value">{{ kpi_data.avg_repair_time }}</div>
                <div class="kpi-label">平均维修天数</div>
                <div class="kpi-change">
                    <i class="fas fa-arrow-down trend-up"></i> -1.5天
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="kpi-card">
                <div class="kpi-value">¥{{ kpi_data.total_asset_value|floatformat:0 }}</div>
                <div class="kpi-label">资产总价值</div>
                <div class="kpi-change">
                    <i class="fas fa-arrow-up trend-up"></i> +8.3%
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="kpi-card">
                <div class="kpi-value">¥{{ kpi_data.maintenance_cost|floatformat:0 }}</div>
                <div class="kpi-label">维修成本</div>
                <div class="kpi-change">
                    <i class="fas fa-arrow-down trend-up"></i> -12.4%
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="kpi-card">
                <div class="kpi-value">{{ kpi_data.stock_health }}%</div>
                <div class="kpi-label">库存健康度</div>
                <div class="kpi-change">
                    <i class="fas fa-arrow-up trend-up"></i> +3.7%
                </div>
            </div>
        </div>
    </div>
    
    <!-- 图表区域 -->
    <div class="row">
        <!-- 趋势分析 -->
        <div class="col-md-8">
            <div class="chart-container">
                <div class="chart-title">资产增长趋势</div>
                <canvas id="trendChart" height="300"></canvas>
            </div>
        </div>
        
        <!-- 异常检测 -->
        <div class="col-md-4">
            <div class="chart-container">
                <div class="chart-title">异常检测</div>
                <div id="anomalyList">
                    {% for anomaly in anomaly_data %}
                    <div class="anomaly-item {{ anomaly.severity }}">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <strong>{{ anomaly.description }}</strong>
                                <br>
                                <small class="text-muted">{{ anomaly.date }}</small>
                            </div>
                            <span class="badge bg-{{ anomaly.severity == 'high' and 'danger' or 'warning' }}">
                                {{ anomaly.severity == 'high' and '高' or '中' }}
                            </span>
                        </div>
                    </div>
                    {% empty %}
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-check-circle fa-2x mb-2"></i>
                        <p>未发现异常情况</p>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
    
    <div class="row">
        <!-- 维修成本趋势 -->
        <div class="col-md-6">
            <div class="chart-container">
                <div class="chart-title">维修成本趋势</div>
                <canvas id="maintenanceTrendChart" height="250"></canvas>
            </div>
        </div>
        
        <!-- 预测分析 -->
        <div class="col-md-6">
            <div class="chart-container">
                <div class="chart-title">维修需求预测</div>
                <div class="forecast-chart">
                    <canvas id="forecastChart" height="250"></canvas>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 对比分析表格 -->
    <div class="row">
        <div class="col-md-6">
            <div class="comparison-table">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>部门</th>
                            <th>资产数量</th>
                            <th>总价值</th>
                            <th>维修成本</th>
                        </tr>
                    </thead>
                    <tbody id="departmentComparisonTable">
                        <!-- 动态加载 -->
                    </tbody>
                </table>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="comparison-table">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>资产类别</th>
                            <th>数量</th>
                            <th>平均价值</th>
                            <th>维修频率</th>
                        </tr>
                    </thead>
                    <tbody id="categoryComparisonTable">
                        <!-- 动态加载 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- 加载指示器 -->
    <div class="loading-spinner" id="loadingSpinner">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
        <p class="mt-2">正在加载数据...</p>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
// 全局变量
let trendChart, maintenanceTrendChart, forecastChart;
const trendData = {{ trend_data|safe }};
const comparisonData = {{ comparison_data|safe }};
const forecastData = {{ forecast_data|safe }};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeCharts();
    loadComparisonTables();
});

// 初始化图表
function initializeCharts() {
    // 资产增长趋势图
    const trendCtx = document.getElementById('trendChart').getContext('2d');
    trendChart = new Chart(trendCtx, {
        type: 'line',
        data: {
            labels: trendData.asset_trend.map(item => item.date),
            datasets: [{
                label: '资产数量',
                data: trendData.asset_trend.map(item => item.count),
                borderColor: '#667eea',
                backgroundColor: 'rgba(102, 126, 234, 0.1)',
                borderWidth: 3,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0,0,0,0.1)'
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });
    
    // 维修成本趋势图
    const maintenanceCtx = document.getElementById('maintenanceTrendChart').getContext('2d');
    maintenanceTrendChart = new Chart(maintenanceCtx, {
        type: 'bar',
        data: {
            labels: trendData.maintenance_trend.map(item => item.month),
            datasets: [{
                label: '维修成本',
                data: trendData.maintenance_trend.map(item => item.total_cost || 0),
                backgroundColor: 'rgba(255, 99, 132, 0.8)',
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '¥' + value.toLocaleString();
                        }
                    }
                }
            }
        }
    });
    
    // 预测分析图
    if (forecastData.maintenance_forecast && forecastData.maintenance_forecast.length > 0) {
        const forecastCtx = document.getElementById('forecastChart').getContext('2d');
        forecastChart = new Chart(forecastCtx, {
            type: 'line',
            data: {
                labels: forecastData.maintenance_forecast.map(item => item.month),
                datasets: [{
                    label: '预测维修数量',
                    data: forecastData.maintenance_forecast.map(item => item.predicted_count),
                    borderColor: '#28a745',
                    backgroundColor: 'rgba(40, 167, 69, 0.1)',
                    borderWidth: 2,
                    borderDash: [5, 5],
                    fill: true
                }, {
                    label: '预测维修成本',
                    data: forecastData.maintenance_forecast.map(item => item.predicted_cost),
                    borderColor: '#ffc107',
                    backgroundColor: 'rgba(255, 193, 7, 0.1)',
                    borderWidth: 2,
                    borderDash: [5, 5],
                    fill: true,
                    yAxisID: 'y1'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top'
                    }
                },
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        beginAtZero: true
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        beginAtZero: true,
                        grid: {
                            drawOnChartArea: false,
                        },
                        ticks: {
                            callback: function(value) {
                                return '¥' + value.toLocaleString();
                            }
                        }
                    }
                }
            }
        });
    }
}

// 加载对比分析表格
function loadComparisonTables() {
    // 部门对比表格
    const departmentTable = document.getElementById('departmentComparisonTable');
    comparisonData.department_comparison.forEach(dept => {
        const row = `
            <tr>
                <td>${dept.name || '未知部门'}</td>
                <td>${dept.asset_count || 0}</td>
                <td>¥${(dept.total_value || 0).toLocaleString()}</td>
                <td>¥${(dept.maintenance_cost || 0).toLocaleString()}</td>
            </tr>
        `;
        departmentTable.innerHTML += row;
    });
    
    // 类别对比表格
    const categoryTable = document.getElementById('categoryComparisonTable');
    comparisonData.category_comparison.forEach(category => {
        const row = `
            <tr>
                <td>${category.name || '未知类别'}</td>
                <td>${category.asset_count || 0}</td>
                <td>¥${(category.avg_value || 0).toLocaleString()}</td>
                <td>${category.maintenance_frequency || 0}次</td>
            </tr>
        `;
        categoryTable.innerHTML += row;
    });
}

// 更新时间范围
function updateDateRange() {
    const select = document.getElementById('dateRangeSelect');
    const customStart = document.getElementById('customStartDate');
    const customEnd = document.getElementById('customEndDate');
    
    if (select.value === 'custom') {
        customStart.style.display = 'block';
        customEnd.style.display = 'block';
    } else {
        customStart.style.display = 'none';
        customEnd.style.display = 'none';
        
        // 自动刷新数据
        refreshDashboard();
    }
}

// 刷新仪表板
function refreshDashboard() {
    const spinner = document.getElementById('loadingSpinner');
    spinner.style.display = 'block';
    
    const dateRange = document.getElementById('dateRangeSelect').value;
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    
    let url = window.location.pathname + '?date_range=' + dateRange;
    if (dateRange === 'custom' && startDate && endDate) {
        url += '&start_date=' + startDate + '&end_date=' + endDate;
    }
    
    // 重新加载页面
    window.location.href = url;
}

// 导出报告
function exportReport() {
    const format = prompt('请选择导出格式:\n1. Excel\n2. PDF\n请输入数字:', '1');
    
    if (format === '1' || format === '2') {
        const exportFormat = format === '1' ? 'excel' : 'pdf';
        const url = `/assets/analytics/export-advanced-report/?type=comprehensive&format=${exportFormat}`;
        
        // 创建下载链接
        const link = document.createElement('a');
        link.href = url;
        link.download = '';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        showAlert('success', '报告导出已开始，请稍候...');
    }
}

// 显示提示信息
function showAlert(type, message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 3秒后自动消失
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 3000);
}

// 实时数据更新（每30秒）
setInterval(() => {
    // 这里可以添加实时数据更新逻辑
    // 例如通过AJAX获取最新的KPI数据
}, 30000);
</script>
{% endblock %}